package cn.school.demo.ui.history

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentHistoryBinding
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.tabs.TabLayoutMediator

class HistoryFragment : Fragment() {
    private lateinit var binding: FragmentHistoryBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_history, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.vw = this
        binding.my = MyApplication.Companion
        init()
        return binding.root
    }

    private fun init() {
        MyApplication.apply {
            systemBarSetting(DARK, requireActivity())
        }
        binding.historyViewPager.adapter = ViewAdapter(this)
        TabLayoutMediator(binding.historyTab, binding.historyViewPager) { tab, position ->
            tab.text = HistoryViewModel().tabTitle[position]
        }.attach()
        //去掉边界阴影
        try {
            val mRecyclerView = binding.historyViewPager.javaClass.getDeclaredField("mRecyclerView")
            mRecyclerView.isAccessible = true
            (mRecyclerView.get(binding.historyViewPager) as RecyclerView).overScrollMode =
                View.OVER_SCROLL_NEVER
        } catch (ignore: Exception) {
            ignore.printStackTrace()
        }
    }

    private inner class ViewAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
        override fun getItemCount(): Int = HistoryViewModel().tabTitle.size

        override fun createFragment(position: Int) = when (position) {
            0 -> HistoryViewPageFragment.newInstance()
            else -> HistoryViewPageSubjectFragment.newInstance()
        }
    }

    fun gotoBack() {
        MyApplication.historyEditOrSave.value = false
        MyApplication.navigateThing["History"]?.let {
            MyApplication.goto(it.toInt(), findNavController(), parentFragmentManager)
        } ?: let {
            //ToastUtils.showLong("系统错误，返回我的界面！")
            LogUtils.e("系统错误，返回我的界面！")
            MyApplication.goto(
                R.id.action_History_to_My,
                findNavController(),
                parentFragmentManager
            )
        }
    }

    fun editORSave() {
        MyApplication.historyEditOrSave.value = !MyApplication.historyEditOrSave.value!!
    }

}